from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from django.http import HttpResponse, JsonResponse
import random

from .constants import *
from meiduo.utils.response_code import *
from celery_tasks.sms.tasks import ccp_send_message_code
from meiduo.libs.captcha.captcha import Captcha


class Images(View):
    """响应html验证图片请求"""
    def get(self, request, uuid):
        key, image_code, image = Captcha.instance().generate_captcha()
        # 获取captcha包生成的密匙、验证码、图片
        conn = get_redis_connection(alias="verification")
        # 连接redis 2#数据库
        conn.setex(uuid, verification_code_expiry, image_code)
        # uuid为键 验证码为值存储在redis数据库

        return HttpResponse(image,content_type="image/png")
        # 将验证图片响应给html页面


class VerifyByMobile(View):
    """响应html手机短信验证"""
    def get(self,request,mobile):
        conn = get_redis_connection(alias="verification")
        if conn.get("sms_%s" % mobile):
            # 判断用户手机号码在规定时间里频繁发送信息
            return render(request,"register.html",{'sms_code_errmsg': "发送信息频繁"})

        data = request.GET
        image_code_get = data.get("image_code", "")
        uuid = data.get("uuid", "")
        if not all([image_code_get,uuid]):
            # 判断数据是否为空
            return render(request,"404.html")

        image_code = conn.get(uuid)
        # 获取redis数据库中uuid对应的image_code

        if image_code is None:
            return JsonResponse({"code": RETCODE.IMAGECODEERR, "errmsg": "图形验证码过期"})
        image_code = image_code.decode()

        if image_code.upper() != image_code_get.upper():
            # 判断用户输入的验证码与数据库中是否一致   注意： 大小写问题 与 转码问题
            return JsonResponse({"code": RETCODE.IMAGECODEERR, "errmsg": "图形验证码输入错误"})

        sms_random_code = '%06d'%random.randint(0, 999999)
        print(sms_random_code)
        # 随机产生短信验证码
        pl = conn.pipeline()
        # 创建redis管道
        pl.delete(uuid)
        # 删除图片验证码数据
        # conn.setex(mobile,message_code_expiry,sms_random_code)
        pl.setex(mobile,message_code_expiry,sms_random_code)
        # 存储sms验证码信息
        # conn.setex("sms_%s"%mobile,again_send_sms_expiry,1)
        pl.setex("sms_%s"%mobile,again_send_sms_expiry, 1)
        # 记录指定手机号已发送过短信状态
        pl.execute()
        # 对redis发送请求

        ccp_send_message_code.delay(mobile,sms_random_code,message_reminder_expiry,templates_num)
        # 利用异步方法
        # CCP().send_template_sms(mobile, [sms_random_code, message_reminder_expiry], templates_num)
        # 请求第三方发送短信验证码
        return JsonResponse({"code": RETCODE.OK, "errmsg": "OK"})




